﻿using AbpApplication.Dto;
using AbpApplication.Expand;
using AbpApplication.InPut;
using AbpEntityFrameworkcore.DbContext;
using AbpToDomain.EntityInfo;
using AbpToDomain.View;
using Application.Expand;
using Flurl.Http;
using LinqSharp;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;
using NLog.LayoutRenderers;
using NStandard;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace AbpApplication.AppServices
{
    public class BaseService : ApplicationService, IBaseService
    {

        private readonly IRepository<Box> Box_res;
        private readonly IRepository<BoxGrid> BoxGrid_res;
        private readonly IRepository<NeetOutMaterial> NeetOutMaterial_res;
        private readonly IRepository<TaskOrder> TaskOrder_res;
        private readonly IRepository<Warehouse> Warehouse_res;
        private readonly IRepository<WarehouseLine> WarehouseLine_res;
        private readonly IRepository<MaterialBase> MaterialBase_res;
        private readonly IRepository<Inlethouse> Inlethouse_res;
        private readonly IRepository<InlethouseLine> Inlethouseline_res;
        private readonly IRepository<lognote> LogNote_res;
        private readonly IRepository<CusetomOrder> cusetom_order_res;
        private readonly IRepository<CusetomOrderLine> cusetom_order_line_res;
        private readonly IRepository<SowingWall> sowingwall_res;
        private readonly IRepository<SowingWallLine> sowingwallLine_res;
        private readonly MyDbContext context;
        private readonly QueryDynamic_WarehouseLine queryDynamic_WarehouseLine;
        private readonly QueryDynamic_Box queryDynamic_Box;
        private readonly ILoginHelper loginHelper;
        public BaseService(
            IRepository<Box> box_res,
            IRepository<BoxGrid> boxGrid_res,
            IRepository<Warehouse> warehouse_res,
            IRepository<WarehouseLine> warehouseLine_res,
            IRepository<MaterialBase> materialBase_res,
            MyDbContext context,
            QueryDynamic_WarehouseLine queryDynamic_WarehouseLine,
            QueryDynamic_Box queryDynamic_Box,
            IRepository<NeetOutMaterial> neetOutMaterial_res,
            IRepository<Inlethouse> inlethouse_res,
            IRepository<InlethouseLine> inlethouseline_res,
            IRepository<TaskOrder> taskOrder_res,
            ILoginHelper loginHelper,
            IRepository<lognote> logNote_res,
            IRepository<CusetomOrder> cusetom_order_res,
            IRepository<CusetomOrderLine> cusetom_order_line_res,
            IRepository<SowingWall> SowingWall_res,
            IRepository<SowingWallLine> sowingwallLine_res)
        {
            Box_res = box_res;
            BoxGrid_res = boxGrid_res;
            Warehouse_res = warehouse_res;
            WarehouseLine_res = warehouseLine_res;
            MaterialBase_res = materialBase_res;
            this.context = context;
            this.queryDynamic_WarehouseLine = queryDynamic_WarehouseLine;
            this.queryDynamic_Box = queryDynamic_Box;
            NeetOutMaterial_res = neetOutMaterial_res;
            Inlethouse_res = inlethouse_res;
            Inlethouseline_res = inlethouseline_res;
            TaskOrder_res = taskOrder_res;
            this.loginHelper = loginHelper;
            LogNote_res = logNote_res;
            this.cusetom_order_res = cusetom_order_res;
            this.cusetom_order_line_res = cusetom_order_line_res;
            this.sowingwall_res = SowingWall_res;
            this.sowingwallLine_res = sowingwallLine_res;
        }
        public async Task<ApiResponse> Create_Boxs(InPut_BaseService input)//配置箱盒
        {
            try
            {
                bool res = await Box_res.AnyAsync(x => x.BoxCode.Substring(x.BoxCode.Length - 4) == input.StartNumber.ToString("D4") || x.BoxCode.Substring(x.BoxCode.Length - 4) == input.EndNumber.ToString("D4"));
                if (res)
                {
                    return new ApiResponse("箱盒已存在", false, null);
                }
                //配置箱盒
                int boxquantity = input.EndNumber - input.StartNumber + 1;
                List<Box> boxes = new List<Box>();
                for (int i = 0; i < boxquantity; i++)//箱
                {
                    Box box = new Box();
                    string BoxCode = "A" + "00000" + (input.StartNumber + i).ToString("D4");
                    box = box.AddBox(BoxCode, input.BoxGridQuantity);
                    List<BoxGrid> boxGrids = new List<BoxGrid>();
                    for (int y = 0; y < input.BoxGridQuantity; y++)//格
                    {
                        BoxGrid boxGrid = new BoxGrid();
                        string BoxGridCode = $"{BoxCode}_{(y + 1).ToString("D2")}";
                        boxGrid = boxGrid.AddBoxGrid(y + 1, BoxGridCode,  box);
                        boxGrids.Add(boxGrid);
                    }
                    await BoxGrid_res.InsertManyAsync(boxGrids);
                    box.BoxGrids.AddRange(boxGrids);
                    boxes.Add(box);
                }
                await Box_res.InsertManyAsync(boxes);
                return new ApiResponse("生成成功", true, null);
            }
            catch(Exception ex)
            {


                loginHelper.LoginAsync(input, "Create_Boxs");
                return new ApiResponse("内部服务器错误", false,null);
            }      
        }
        public async Task<ApiResponse> Create_Warehouses(InPut_BaseService3 input)//配置库位
        {
            try
            {
                bool res= await Warehouse_res.AnyAsync(x=>x.WarehouseCode == input.WarehouseCode);
                if (res)
                {
                    return new ApiResponse("库位名称重复", false, null);
                }
                Warehouse warehouse = new Warehouse();
                warehouse = warehouse.AddWarehouse(input.WarehouseCode, input.Xaxis, input.Yaxis, input.Zaxis);
                await Warehouse_res.InsertAsync(warehouse);
                int sum = input.Xaxis * input.Yaxis * input.Zaxis;
                List<WarehouseLine> lines = new List<WarehouseLine>();           
                    //排
                for (int j = 1; j <= input.Xaxis; j++)
                    {
                        //高
                        for (int k = 1; k <= input.Yaxis; k++)
                        {
                            //列
                            for (int y = 1; y <= input.Zaxis; y++)
                            {
                                WarehouseLine warehouseLine = new WarehouseLine();
                                warehouseLine = warehouseLine.AddWarehouseline(input.Long, input.Wide,input.high, j, k, y, warehouse);
                                warehouseLine.WarehouseLineCode = warehouse.WarehouseCode + "-" + j.ToString("D3") + "-" + k.ToString("D3") + "-" + y.ToString("D2");
                                lines.Add(warehouseLine);
                            }
                        }
                    }              
                warehouse.warehouselines.AddRange(lines);
                await Warehouse_res.InsertAsync(warehouse);
                await WarehouseLine_res.InsertManyAsync(lines);
                return new ApiResponse("配置成功", true, null);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(input, "Create_Warehouses");
                return new ApiResponse("内部错误服务器", false,null);
            }

        }
        public async Task<ApiResponse> Update_Box(InPut_BaseService2 input)//更改箱盒
        {
            try
            {
                var boxs = await Box_res.WithDetailsAsync();
                Box box=await  boxs.FirstOrDefaultAsync(x=>x.BoxCode == input.BoxCode);
                if (box==null) return new ApiResponse("未查询到料盒", false, null);
                foreach (var item in box.BoxGrids)
                {
                    if (item.MaterialBases.Count()>0)
                    {
                        return new ApiResponse("料盒中有物料不允许修改", false, null);
                    }
                }
                box.BoxCode = input.BoxCode;
                box.BoxGrids.Clear();
                await Box_res.UpdateAsync(box);
                List<BoxGrid> boxGrids = new List<BoxGrid>();
                for (int i = 0; i < input.BoxGridQuantity; i++)
                {
                    BoxGrid boxGrid = new BoxGrid();
                    string BoxGridCode = $"{box.BoxCode}_{(i + 1).ToString("D2")}";
                    boxGrid = boxGrid.AddBoxGrid(i + 1, BoxGridCode, box);
                    boxGrids.Add(boxGrid);
                }
                await BoxGrid_res.InsertManyAsync(boxGrids);
                box.BoxGrids.Clear();
                box.BoxGrids.AddRange(boxGrids);
                box.BoxGridQuantity = (int)input.BoxGridQuantity;
                await Box_res.UpdateAsync(box);
                return new ApiResponse("更新成功", true, null);
                //var boxs = await Box_res.WithDetailsAsync();
                //foreach (var boxcode in input.BoxCode)
                //{
                //    Box box = boxs.FirstOrDefault(x => x.BoxCode == boxcode);
                //    if (box == null)
                //    {
                //        return new ApiResponse("未查询到", false, null);
                //    }                
                //    box.BoxGrids .Clear();
                //    await Box_res.UpdateAsync(box);
                //    await UnitOfWorkManager.Current.SaveChangesAsync();

                //    List<BoxGrid> boxGrids = new List<BoxGrid>();
                //    for (int i = 0; i < input.BoxGridQuantity; i++)
                //    {
                //        BoxGrid boxGrid = new BoxGrid();
                //        string BoxGridCode = $"{box.BoxCode}_{(i + 1).ToString("D2")}";
                //        boxGrid = boxGrid.AddBoxGrid(i + 1, BoxGridCode, box);              
                //        boxGrids.Add(boxGrid);

                //    }
                //    await BoxGrid_res.InsertManyAsync(boxGrids);
                //    box.BoxGrids.Clear();
                //    box.BoxGrids.AddRange(boxGrids);
                //    box.BoxGridQuantity = (int)input.BoxGridQuantity;
                //    await Box_res.UpdateAsync(box);

                //}
                //return new ApiResponse("更新成功", true, null);

            }
           catch (Exception ex)
            {              
                loginHelper.LoginAsync(input, "Update_Box");
                return new ApiResponse("内部服务器错误", false,null);
            }


        }   
        public async Task<ApiResponsePage> GetList_WarehouseLine(InPut_BaseService4 inPut)  //获取仓位列表  
        {

            try
            {
                var warehouseLines = queryDynamic_WarehouseLine.QueryDynameic(inPut.WarehouseCode, inPut.Long, inPut.Wide, inPut.high, inPut.Xaxis, inPut.Yaxis, inPut.Zaxis, inPut.IsEnable);
                long count = warehouseLines.LongCount();//计算出了总条数
                long pageCount = (long)Math.Ceiling(count * 1.0 / inPut.PageSize);
                warehouseLines = warehouseLines.SelectPage(inPut.PageIndex, inPut.PageSize).ToList();
                return new ApiResponsePage("获取成功", true, warehouseLines, count, pageCount);
            }
            catch (Exception ex)
            {
          
                loginHelper.LoginAsync(inPut, "GetList_WarehouseLine");
                return new ApiResponsePage("内部服务器错误", false, null,null,null);
            }


        }
        public async Task<ApiResponse> test(request request)
        {

            Box box = await Box_res.FirstOrDefaultAsync(x => x.BoxCode == "A000000001");
            return new ApiResponse($"任务单中有料盒已被添加到任务,暂时不允许分配", true, null);
        
        }
        public async Task<ApiResponse> Update_WarehouseLines(InPut_BaseService5 inPut)//更新仓位状态
        {
            try
            {
                foreach (var item in inPut.WarehouseLineCodes)
                {
                    WarehouseLine warehouseLine = await WarehouseLine_res.FirstOrDefaultAsync(x => x.WarehouseLineCode == item);
                    if (warehouseLine != null)
                    {
                        warehouseLine.IsEnable = inPut.Type;
                    }
                    await WarehouseLine_res.UpdateAsync(warehouseLine);
                }
                return new ApiResponse("修改成功", true, null);

            }
            catch(Exception ex)
            {              
                loginHelper.LoginAsync(inPut, "Update_WarehouseLines");
                return new ApiResponse("内部服务器错误", false, null);
            }



        }
        public async Task<ApiResponsePage> GetList_Boxs(InPut_BaseService6 inPut)
        {
            try
            {
                var boxs = queryDynamic_Box.QueryDynameic(inPut.BoxCode);
                long count = boxs.LongCount();//计算出了总条数
                long pageCount = (long)Math.Ceiling(count * 1.0 / inPut.PageSize);
                boxs = boxs.SelectPage(inPut.PageIndex, inPut.PageSize).ToList();
                return new ApiResponsePage("获取成功", true, boxs, count, pageCount);
            }
            catch (Exception ex)
            {             
                loginHelper.LoginAsync(inPut, "GetList_WarehouseLine");
                return new ApiResponsePage("内部服务器错误", false, null, null, null);
            }

        }//获取箱盒
        public async Task<ApiResponse> CreateMaterialBase(InPut_BaseService7 inPut)//新料入库
        {
            try
            {
         


                var boxgrids=await BoxGrid_res.WithDetailsAsync();
                BoxGrid boxGrid = new BoxGrid();
                boxGrid = await boxgrids.FirstOrDefaultAsync(x => x.BoxGridCode.Contains(inPut.BoxGridCode.Substring(0,10)));
                if (boxGrid.TheBox.BoxGridQuantity <= 6 && inPut.BoxGridCode.Length > 10)
                {
                    return new ApiResponse("小于6格请扫箱号", false, null);
                }
                if (boxGrid.TheBox.BoxGridQuantity >= 8 && inPut.BoxGridCode.Length <= 10)
                {
                    return new ApiResponse("大于6格请扫格口号", false, null);
                }
                if (inPut.BoxGridCode.Length == 12)
                    {
                        int lastCharIndex = inPut.BoxGridCode.Length - 1;
                        char lastChar = inPut.BoxGridCode[lastCharIndex];
                        inPut.BoxGridCode = inPut.BoxGridCode.Substring(0, lastCharIndex) + "0" + lastChar;
                        boxGrid = await boxgrids.FirstOrDefaultAsync(x => x.BoxGridCode.Contains(inPut.BoxGridCode));
                }
                else
                {
                    boxGrid = await boxgrids.FirstOrDefaultAsync(x => x.BoxGridCode.Contains(inPut.BoxGridCode)&&x.MaterialBases.Count==0);
                    if(boxGrid == null)
                    {
                        return new ApiResponse("无空格口可用", false, null);
                    }
                }
                if (boxGrid == null) return new ApiResponse("未查询到该料箱", false, null);
                if (boxGrid.TheBox.WarehouseLine != null) return new ApiResponse("该料箱当前在货仓中,无法新增料", false, null);

              
                var MaterialBases=   await MaterialBase_res.WithDetailsAsync();
                MaterialBase materialBaseJudge = await MaterialBases.FirstOrDefaultAsync(x => x.MaterialCode == inPut.MaterialCode&&x.BoxGrid!=null);
                if (materialBaseJudge != null) return new ApiResponse("已存在物料", false, null);
                #region  operate
                //creater materialbase 
                MaterialBase materialBaseModel = await MaterialBases.FirstOrDefaultAsync(x => x.MaterialCode == inPut.MaterialCode && x.BoxGrid == null);
                MaterialBase materialBase = new MaterialBase();
                if (materialBaseModel == null)
                {                
                    materialBase = materialBase.AddMaterialBase(inPut.Quantity, inPut.Batch, inPut.MaterialCode, inPut.MaterialName, boxGrid);
                    await MaterialBase_res.InsertAsync(materialBase);
                    boxGrid.MaterialBases.Add(materialBase);
                }
                else
                {
                    materialBaseModel.Quantity = inPut.Quantity;
                    await MaterialBase_res.UpdateAsync(materialBaseModel);
                    boxGrid.MaterialBases.Add(materialBaseModel);
                }
            
                //update boxgrid        
                await BoxGrid_res.UpdateAsync(boxGrid);
                return new ApiResponse("加入料盒成功", true, null);
                #endregion
            }
            catch(Exception ex)
            {
              
                loginHelper.LoginAsync(inPut, "CreateMaterialBase");
                return new ApiResponse("内部错误服务器", false, null);
            }

        }
        public async Task<ApiResponse> CreateNeetOutMaterial(InPut_BaseService10 InPut)//手动出库-添加需出料-添加agv任务 🆗
        {
            try
            {
                InPut. MaterialCodes = InPut.MaterialCodes.Distinct().ToList();
                //List<MaterialBase> materialBases = await MaterialBase_res.GetListAsync(x =>InPut. MaterialCodes.Any(y => y == x.MaterialCode));
                List<MaterialBase> materialBases=  MaterialBase_res.WithDetails().ToList();    
                List<NeetOutMaterial> NeetOutMaterials = await NeetOutMaterial_res.GetListAsync(x => InPut.MaterialCodes.Any(y => y == x.Material.MaterialCode));
                List<string> MaterialCodesDel= NeetOutMaterials.Select(x => x.Material.MaterialCode).ToList();
                InPut. MaterialCodes= InPut.MaterialCodes.Except(MaterialCodesDel).ToList();
                materialBases = materialBases.Where(x => InPut.MaterialCodes.Any(y => y == x.MaterialCode)).ToList();
                //var taskOrders = await TaskOrder_res.GetListAsync(x => materialBases.Any(y => y.Info== x.Box.BoxCode));
                var taskOrders = context.taskOrders.Include(x=>x.Box).ToList();
                taskOrders = taskOrders.Where(x => materialBases.Any(y => y.BoxGrid.TheBox.BoxCode == x.Box.BoxCode && x.Type == "出库")).ToList();
                List<TaskOrder>taskOrderLussed= taskOrders.Where(x => x.State == "已下发").ToList();
                if(taskOrderLussed.Count>0)
                {
                    return new ApiResponse(taskOrders[0].Box.BoxCode+"已发送AGV任务,无法再次添加出库", false, null);
                }
                #region operate
                //creater neetOutMaterial
                List<NeetOutMaterial> neetOutMaterials = new List<NeetOutMaterial>();
                foreach (var materialBase in materialBases)
                {
                    NeetOutMaterial neetOutMaterial = new NeetOutMaterial();
                    neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, null,null,null,null,null);
                    neetOutMaterials.Add(neetOutMaterial);
                    materialBase.NeetOutMaterials.Add(neetOutMaterial);
                }
                await NeetOutMaterial_res.InsertManyAsync(neetOutMaterials);
                await MaterialBase_res.UpdateManyAsync(materialBases);
                //creater taskorder
                if(InPut.InlethouseCode !="3")
                {
                    materialBases = materialBases.DistinctBy(x => x.BoxGrid.TheBox.BoxCode).ToList();
                    List<TaskOrder> taskOrderNotfinsih = taskOrders.Where(x => x.State == "未下发").ToList();
                    materialBases = materialBases.Where(x => !taskOrderNotfinsih.Any(y => y.Box.BoxCode == x.BoxGrid.TheBox.BoxCode)).ToList();//去掉已在任务中有的箱盒
                    foreach (var item in materialBases)
                    {
                        TaskOrder taskOrder = new TaskOrder();
                        taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, InPut.InlethouseCode, null);
                        item.BoxGrid.TheBox.TaskOrder = taskOrder;
                        await Box_res.UpdateAsync(item.BoxGrid.TheBox);
                        await TaskOrder_res.InsertAsync(taskOrder);
                    }
                    return new ApiResponse("已添加至需出料", true, null);
                }
                else
                {
                    //3号台
                    materialBases = materialBases.DistinctBy(x => x.BoxGrid.TheBox.BoxCode).ToList();
                    List<TaskOrder> taskOrderNotfinsih = taskOrders.Where(x => x.State == "未下发").ToList();
                    materialBases = materialBases.Where(x => !taskOrderNotfinsih.Any(y => y.Box.BoxCode == x.BoxGrid.TheBox.BoxCode)).ToList();//去掉已在任务中有的箱盒
                    List<SowingWallLine> sowingWallLines=   await sowingwallLine_res.GetListAsync(x => x.IsOccupy == false && x.BoxCode == null);
                    if(sowingWallLines.Count < materialBases.Count) return new ApiResponse("可用缓存位不够", false, null);
           
                    foreach (var item in materialBases)
                    {

                        TaskOrder taskOrder = new TaskOrder();
                        foreach (var sowingWallLine in sowingWallLines)
                        {
                            if (sowingWallLine.IsOccupy)
                            {
                                continue;
                            }
                            taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, sowingWallLine.SowingWallLine_Name, null);
                            sowingWallLine.IsOccupy = true;
                        }
                   
                        item.BoxGrid.TheBox.TaskOrder = taskOrder;
                        await Box_res.UpdateAsync(item.BoxGrid.TheBox);
                        await TaskOrder_res.InsertAsync(taskOrder);
                    }
                    await sowingwallLine_res.UpdateManyAsync(sowingWallLines);
                    return new ApiResponse("已添加至需出料", true, null);
                }
                #endregion
            }
            catch (Exception ex)
            {
              
                loginHelper.LoginAsync(InPut, "CreateNeetOutMaterial");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> DeleteMaterial(InPut_BaseService8 InPut)//取料确认
        {
            try
            {
               var neetOutMaterials=  await NeetOutMaterial_res.WithDetailsAsync();  
                NeetOutMaterial neetOutMaterial=  await neetOutMaterials.FirstOrDefaultAsync
                (x=>x.Material.MaterialCode == InPut.MaterialCode&&x.Material.BoxGrid.BoxGridCode.Contains(InPut.BoxCode));         
                if (neetOutMaterial == null) return new ApiResponse("未查询到有物料需出库/该物料存在库中", false, null);
                Box box=  await Box_res.FirstOrDefaultAsync(x=>x.BoxCode == InPut.BoxCode);
                //if(box.Id_WarehouseLine!=null) return new ApiResponse("料盒未下架,无法出库", false, null);
                #region operate
                var MaterialBases = await MaterialBase_res.WithDetailsAsync();
                MaterialBase materialBaseDel = await MaterialBases.FirstOrDefaultAsync(x => x.Id_Materialbase == neetOutMaterial.Material.Id_Materialbase);
                BoxGrid boxGrid = await BoxGrid_res.FirstOrDefaultAsync(x => x.Id_BoxGrid == materialBaseDel.BoxGrid.Id_BoxGrid);
                if(materialBaseDel.Quantity<neetOutMaterial.NeetQuantity) return new ApiResponse("物料被超发,请调整数量", false, null);
                //日志记录
                lognote lognote = new lognote();
                lognote.DateTime = DateTime.Now;
                lognote.User = InPut.JWTUser;
                lognote.Type = "取料";
                lognote.Note = materialBaseDel.MaterialCode + "物编"+ materialBaseDel.MaterialName+"从" + boxGrid.BoxGridCode + "被取出" + "需求数量是"+ neetOutMaterial.NeetQuantity+"物料数量是"+ materialBaseDel.Quantity;
                lognote.MaterialCode = materialBaseDel.MaterialCode;
                lognote.MaterialName = materialBaseDel.MaterialName;
                lognote.Batch = materialBaseDel.Batch;
                lognote.OrderNo = neetOutMaterial.OrderNo;
                lognote.Size = neetOutMaterial.NeetQuantity.ToString();
                await LogNote_res.InsertAsync(lognote);
                if (materialBaseDel.Quantity - neetOutMaterial.NeetQuantity <= 0||neetOutMaterial.NeetQuantity==0||string.IsNullOrEmpty(neetOutMaterial.NeetQuantity.ToString()))
                {
                    materialBaseDel.BoxGrid = null;
                    await MaterialBase_res.UpdateAsync(materialBaseDel);
                }
                else
                {
                    materialBaseDel.Quantity = materialBaseDel.Quantity - neetOutMaterial.NeetQuantity;
                    await MaterialBase_res.UpdateAsync(materialBaseDel);
                }
                //删除需出料
                BaseDto baseDto = new BaseDto();
                baseDto.NeetQuantity = neetOutMaterial.NeetQuantity;
                baseDto.BoxGridCode = boxGrid.BoxGridCode;
                baseDto.moCode = neetOutMaterial.moCode;
                baseDto.hSerial = neetOutMaterial.OrderNo;
                baseDto.slotNum = neetOutMaterial.slotNum;
                await NeetOutMaterial_res.DeleteAsync(neetOutMaterial);
                return new ApiResponse("出库成功", true, baseDto);
                #endregion
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(InPut, "DeleteMaterial");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> GetDeleteMaterial(InPut_BaseService8 InPut)//拿到出库数据  不出
        {
            try
            {
                var neetOutMaterials = await NeetOutMaterial_res.WithDetailsAsync();
                NeetOutMaterial neetOutMaterial = await neetOutMaterials.FirstOrDefaultAsync
                (x => x.Material.MaterialCode == InPut.MaterialCode && x.Material.BoxGrid.BoxGridCode.Contains(InPut.BoxCode));
                if (neetOutMaterial == null) return new ApiResponse("未查询到有物料需出库/该物料存在库中", false, null);
                Box box = await Box_res.FirstOrDefaultAsync(x => x.BoxCode == InPut.BoxCode);
                //if(box.Id_WarehouseLine!=null) return new ApiResponse("料盒未下架,无法出库", false, null);
                #region operate
                var MaterialBases = await MaterialBase_res.WithDetailsAsync();
                MaterialBase materialBaseDel = await MaterialBases.FirstOrDefaultAsync(x => x.Id_Materialbase == neetOutMaterial.Material.Id_Materialbase);

                BoxGrid boxGrid = await BoxGrid_res.FirstOrDefaultAsync(x => x.Id_BoxGrid == materialBaseDel.BoxGrid.Id_BoxGrid);
                //删除需出料
                BaseDto baseDto = new BaseDto();
                baseDto.NeetQuantity = neetOutMaterial.NeetQuantity;
                baseDto.BoxGridCode = boxGrid.BoxGridCode;
                baseDto.moCode = neetOutMaterial.moCode;
                baseDto.hSerial = neetOutMaterial.OrderNo;
                baseDto.slotNum = neetOutMaterial.slotNum;
                return new ApiResponse("出库成功", true, baseDto);
                #endregion
            }
            catch (Exception ex)
            {

                loginHelper.LoginAsync(InPut, "GetDeleteMaterial");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> Create_Inlethouses(InPut_BaseService9 input)//配置缓存货位
        {
            try
            {
                bool res = await   Inlethouse_res .AnyAsync(x => x.InlethouseCode == input.InlethouseCode);
                if (res)
                {
                    return new ApiResponse("库位名称重复", false, null);
                }
                Inlethouse inlethouse = new Inlethouse();
                inlethouse = inlethouse.AddInlethouse(input.InlethouseCode, input.Xaxis, input.Yaxis, input.Zaxis);
                await Inlethouse_res.InsertAsync(inlethouse);
                int sum = input.Xaxis * input.Yaxis * input.Zaxis;
                List<InlethouseLine> lines = new List<InlethouseLine>();
                //排
                for (int j = 1; j <= input.Xaxis; j++)
                {
                    //高
                    for (int k = 1; k <= input.Yaxis; k++)
                    {
                        //列
                        for (int y = 1; y <= input.Zaxis; y++)
                        {
                            InlethouseLine inlethouseLine = new InlethouseLine();
                            inlethouseLine = inlethouseLine.AddInlethouseline(input.Long, input.Wide, input.high, j, k, y, inlethouse,input.Type);
                            inlethouseLine.InlethouseLineCode = inlethouse.InlethouseCode + "-" + j.ToString("D2") + "-" + k.ToString("D2") + "-" + y.ToString("D2");
                            lines.Add(inlethouseLine);
                        }
                    }
                }
                inlethouse.inlethouselines.AddRange(lines);
                await Inlethouse_res.InsertAsync(inlethouse);
                await Inlethouseline_res.InsertManyAsync(lines);
                return new ApiResponse("配置成功", true, null);
            }
            catch (Exception ex)
            {
            

                loginHelper.LoginAsync(input, "Create_Inlethouses");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> Create_Inlethouse(InPut_BaseService9 input)
        {
            try
            {

                bool result=    await Inlethouseline_res.AnyAsync(x=>x.Xaxis == input.Xaxis&&x.Yaxis==input.Yaxis&&x.Zaxis==input.Zaxis);
                if(result) return new ApiResponse("入出.库口已存在", false, null);
                Inlethouse inlethouse = new Inlethouse();
                inlethouse = inlethouse.AddInlethouse(input.InlethouseCode, input.Xaxis, input.Yaxis, input.Zaxis);
                InlethouseLine inlethouseLine = new InlethouseLine();
                inlethouseLine = inlethouseLine.AddInlethouseline(input.Long, input.Wide, input.high, input.Xaxis, input.Yaxis, input.Zaxis,null, input.Type);
                inlethouseLine.InlethouseLineCode = input.InlethouseCode + "-" + input.Xaxis.ToString("D2") + "-" + input.Yaxis.ToString("D2") + "-" + input.Zaxis.ToString("D2");
                inlethouseLine.TheInlethouse = inlethouse;
                inlethouse.inlethouselines.Add(inlethouseLine);
                await Inlethouse_res.InsertAsync(inlethouse);
                await Inlethouseline_res.InsertAsync(inlethouseLine);
                return new ApiResponse("配置成功", true, null);
            }
            catch(Exception ex)
            {
            

                loginHelper.LoginAsync(input, "Create_Inlethouse");
                return new ApiResponse("内部错误服务器", false, null);
            }
   
        }//配置入库口
        public async Task<ApiResponse> GetList_InlethouesCode(string Type)
        {
            try
            {
                List<InlethouseLine> inlethouseLines=   await Inlethouseline_res.GetListAsync(x=>x.Type == Type);
                List<string> InlethouseCodes=inlethouseLines.Select(x=>x.InlethouseLineCode).ToList();
                return new ApiResponse("获取成功",true, InlethouseCodes);
            }
            catch (Exception ex)
            {
                Logger.LogWarning($"GetList_InlethouesCode-{Type}");

     
                return new ApiResponse("内部错误服务器", false, null);
            }
        }//获取出口
        public async Task<ApiResponse> UpdateTaskOrderState(InPut_BaseService11 InPut)//修改任务状态
        {
            try
            {
                TaskOrder taskOrder=await TaskOrder_res.FirstOrDefaultAsync(x=>x.TaskOrderCode == InPut.TaskOrderCode);
                if (taskOrder == null)
                {
                    return new ApiResponse("未查询到单号", false, null);
                }
                taskOrder.State=InPut.Type;
                await TaskOrder_res.UpdateAsync(taskOrder);
                return new ApiResponse("修改成功", true, null);
            }
            catch (Exception ex)
            {
               

                loginHelper.LoginAsync(InPut, "UpdateTaskOrderState");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> CreateTaskOrder(InPut_BaseService12 InPut)//手动入库 🆗
        {
            try
            {
                Box box =  await context.boxs.Include(x => x.WarehouseLine).FirstOrDefaultAsync(x=>x.BoxCode==InPut.BoxCode);
                List<WarehouseLine>  warehouseLines = await WarehouseLine_res.GetListAsync(x => x.Box == null&&x.IsEnable==true&&x.IsOccupy==false);
                WarehouseLine  warehouseLine=warehouseLines.OrderBy(x=>Random.Shared.Next()).First();
                InlethouseLine inlethouseLine = await Inlethouseline_res.FirstOrDefaultAsync(x => x.InlethouseLineCode == InPut.InlethouseCode);                                   
                if (box == null)
                {
                    return new ApiResponse("未查询到箱盒", false, null);
                }
                if (box.WarehouseLine != null)
                {
                    return new ApiResponse("箱盒已在货架上", false, null);
                }
                bool res=  await TaskOrder_res.AnyAsync(x=>x.Id_Box==box.Id_Box);
                if (res) return new ApiResponse("已存在相同箱盒任务/或者任务还没结束,检查ESS任务系统去！！！", false, null);
                TaskOrder taskOrder = new TaskOrder();
                taskOrder.Box= box;
                taskOrder.Type = "入库";
                taskOrder.WarehouseCode = warehouseLine.WarehouseLineCode;
                taskOrder.InlethouseCode = inlethouseLine.InlethouseLineCode;
                taskOrder.CreatTime=DateTime.Now;
                taskOrder.State = "未下发";
                taskOrder.TaskOrderCode= ExtendRandom.CreateRandom();
                box.TaskOrder = taskOrder;
                await Box_res.UpdateAsync(box);
                await TaskOrder_res.InsertAsync(taskOrder);
                await UnitOfWorkManager.Current.SaveChangesAsync();
                warehouseLine.IsOccupy = true;
                await WarehouseLine_res.UpdateAsync(warehouseLine);
                return new ApiResponse("任务生成成功", true, taskOrder.TaskOrderCode);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(InPut, "CreateTaskOrder");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> CreateTaskOrderOut(InPut_BaseService13 InPut)//手动出nu库 🆗
        {
            try
            {
                List<TaskOrder> taskOrders = await TaskOrder_res.WithDetails().ToListAsync();
                List<TaskOrder> taskOrdersDel = taskOrders.Where(x => InPut.BoxCodes.Any(y => y == x.Box.BoxCode)).ToList();
                List<Box> boxes = await Box_res.WithDetails().ToListAsync();
                boxes = boxes.Where(x => InPut.BoxCodes.Any(y => y == x.BoxCode)).ToList();
                boxes = boxes.Where(x => !taskOrdersDel.Any(y => y.Id_Box == x.Id_Box)).ToList();
                List<TaskOrder> taskOrdersInsert = new List<TaskOrder>();
                if (InPut.InlethouseCode != "3")
                {
                    foreach (var item in boxes)
                    {
                        TaskOrder taskOrder = new TaskOrder();
                        taskOrder = taskOrder.AddTaskOrder("出库", item, item.WarehouseLine.WarehouseLineCode, InPut.InlethouseCode, null);
                        taskOrdersInsert.Add(taskOrder);
                    }
                }
                else
                {
                    List<SowingWallLine> sowingWallLines = await sowingwallLine_res.GetListAsync(x => x.IsOccupy == false && string.IsNullOrEmpty( x.BoxCode));
                    if (sowingWallLines.Count < boxes.Count) return new ApiResponse("可用缓存位不够", false, null);
                    foreach (var item in boxes)
                    {
                        TaskOrder taskOrder = new TaskOrder();
                        foreach (var sowingWallLine in sowingWallLines)
                        {
                            if (sowingWallLine.IsOccupy)
                            {
                                continue;
                            }
                            taskOrder = taskOrder.AddTaskOrder("出库", item, item.WarehouseLine.WarehouseLineCode, sowingWallLine.SowingWallLine_Name, "pda");
                            taskOrdersInsert.Add(taskOrder);
                            sowingWallLine.IsOccupy = true;
                            break;
                        }
                
                    }
                    await sowingwallLine_res.UpdateManyAsync(sowingWallLines);
                }

                await TaskOrder_res.InsertManyAsync(taskOrdersInsert);
                return new ApiResponse("任务生成成功", true, null);
            }
            catch (Exception ex)
            {
               

                loginHelper.LoginAsync(InPut, "CreateTaskOrderOut");
                return new ApiResponse("内部错误服务器", false, null);
            }


        }
        public async Task<ApiResponse> DeleteTaskOrder(List<string> TaskOrderCodes)
        {
            try
            {
                List<TaskOrder> taskOrders = await TaskOrder_res.GetListAsync(x => TaskOrderCodes.Any(y => y == x.TaskOrderCode));
                foreach (var taskOrder in taskOrders)
                {
                    if (taskOrder.State == "已下发")
                    {
                        continue;
                    }
                    if (!string.IsNullOrEmpty( taskOrder.OrderNo) &&taskOrder.OrderNo.Contains("pda"))
                    {
                       SowingWallLine sowingWallLine=  await sowingwallLine_res.FirstOrDefaultAsync(x => x.SowingWallLine_Name == taskOrder.InlethouseCode);
                        if (sowingWallLine != null)
                        {
                            sowingWallLine.IsOccupy = false;
                            await sowingwallLine_res.UpdateAsync(sowingWallLine);
                        }
                    }
                    await TaskOrder_res.DeleteAsync(taskOrder);
                }
              
                return new ApiResponse("删除成功", true, null);
            }catch (Exception ex)
            {

                loginHelper.LoginAsync(TaskOrderCodes, "UpdateTaskOrderState");
                return new ApiResponse("内部错误服务器", false, null);
            }
     
        }//删除任务
        public async Task<ApiResponse> MergeBox(InPut_BaseService14 InPut)//合箱
        {
            try
            {
                MaterialBase materialBase = await MaterialBase_res.FirstOrDefaultAsync(x => x.BoxGrid.TheBox.BoxCode == InPut.BoxCode && x.MaterialCode == InPut.MaterialCode);
                if (materialBase == null) return new ApiResponse("未查询到相应的货物", false, null);
                BoxGrid boxGrid = await BoxGrid_res.FirstOrDefaultAsync(x => x.BoxGridCode == InPut.NBoxCodeGrid);
                if (boxGrid == null) return new ApiResponse("未查询到空余的新格口", false, null);
                List<Box> boxes = await Box_res.WithDetails().ToListAsync();
                Box box = boxes.FirstOrDefault(x => x.BoxCode == InPut.BoxCode);
                Box Nbox = boxes.FirstOrDefault(x => x.BoxCode == boxGrid.TheBox.BoxCode);
                if (box.WarehouseLine != null || Nbox.WarehouseLine != null) return new ApiResponse("料箱还在货架上,无法合箱", false, null);
                //operate
                materialBase.BoxGrid = boxGrid;
                boxGrid.MaterialBases.Add(materialBase);
                await MaterialBase_res.UpdateAsync(materialBase);
                await BoxGrid_res.UpdateAsync(boxGrid);
                //log
                lognote lognote=new lognote();
                lognote.Type = "修改";

                return new ApiResponse("合箱成功", true, null);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(InPut, "MergeBox");
                return new ApiResponse("合箱失败", false, null);
            }
       
        }
        public async Task<ApiResponse> CreateLog(InPut_BaseService15 InPut)//添加日志
        {
            lognote lognote = new lognote();
            lognote.DateTime = DateTime.Now;
            lognote.User=InPut.User;
            lognote.Type = InPut.Type;
            lognote.Note = InPut.Note;
            await LogNote_res.InsertAsync(lognote);
            return new ApiResponse("添加成功",true, null);
        }
        public async Task<ApiResponse> UpdateNeetQuantity(InPut_BaseService16 InPut)//编辑需求出库数量
        {
            try
            {
                var NeetMaterials=  await NeetOutMaterial_res.WithDetailsAsync();
                NeetOutMaterial neetOutMaterial = await NeetMaterials.FirstOrDefaultAsync(x => x.Id_NeetOutMaterial == InPut.Id_NeetOutMaterial);
                if (neetOutMaterial == null) return new ApiResponse("查询不到的数据", false, null);
                if(neetOutMaterial.Material.Quantity<InPut.NeetQuantity) return new ApiResponse("需求数量不能大于库存数量", false, null);
                neetOutMaterial.NeetQuantity = InPut.NeetQuantity;
                await NeetOutMaterial_res.UpdateAsync(neetOutMaterial);
                return new ApiResponse("调整成功", true, null);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(InPut, "UpdateNeetQuantity");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> GetNeetBoxMaterial(string BoxCode)
        {
            try
            {
                List<View_NeetOutMaterial> view_NeetOutMaterials = context.View_NeetOutMaterials.Where(x => x.BoxGridCode.Contains(BoxCode)).ToList();
                return new ApiResponse("获取成功", true, view_NeetOutMaterials);
            }
            catch(Exception ex)
            {
                loginHelper.LoginAsync(BoxCode, "GetNeetBoxMaterial");
                return new ApiResponse("内部错误服务器", false, null);
            }
          
        }//获取需求出库 -图形
        public async Task<ApiResponse> GetWarehousequantity()//仓库使用数量
        {
            try
            {
                BaseDto2 baseDto2 = new BaseDto2();
                baseDto2.Usecount = await context.warehouseLines.Where(x => x.Box != null).CountAsync();
                baseDto2.Notusecount = await context.warehouseLines.Where(x => x.Box == null).CountAsync();
                baseDto2.Allcount = await context.warehouseLines.Where(x => true).CountAsync();
                return new ApiResponse("获取成功", true, baseDto2);
            }
            catch(Exception ex)
            {
                loginHelper.LoginAsync("", "GetWarehousequantity");
                return new ApiResponse("内部错误服务器", false, null);
            }
      
        }
        public async Task<ApiResponse> Revoke_MaterialBase(string LPN)//删除在盒物料
        {
            try
            {
                var materialBasesQuery = await MaterialBase_res.WithDetailsAsync();
                MaterialBase materialBase = await materialBasesQuery.FirstOrDefaultAsync(x => x.MaterialCode == LPN);
                if (materialBase == null) return new ApiResponse("未查询到LPN", false, null);
                if (materialBase.BoxGrid.TheBox.WarehouseLine != null) return new ApiResponse("物料在库内,无法删除", false, null);
                await MaterialBase_res.DeleteAsync(materialBase);
                return new ApiResponse("删除成功", true, null);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(LPN, "Delete_MaterialBase");
                return new ApiResponse("内部错误服务器", false, null);
            }
     
        }
        public async Task<ApiResponse> GetListCusetom(InPut_BaseService17 InPut)
        {
            try
            {
                List<CusetomOrder> cusetomOrders = await cusetom_order_res.GetListAsync(x=>x.State.Contains(InPut.State));
                if (!string.IsNullOrEmpty(InPut.MoCode))
                {
                    cusetomOrders= cusetomOrders.Where(x=>x.moCode.Contains(InPut.MoCode)
                    ).ToList();
                }
                return new ApiResponse("获取成功", true, cusetomOrders.Take(200));
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync("state", "GetListCusetom");
                return new ApiResponse("内部错误服务器", false, null);
            }

        }//获取mes出库工单
        public async Task<ApiResponse> CreateTaskNeetOut(InPut_BaseService20 InPut)//分配mes出库工单  
        {
            var cusetomOrders=await cusetom_order_res.WithDetailsAsync();
            CusetomOrder cusetomOrder = await cusetomOrders.FirstOrDefaultAsync (x => x.CusetomOrder_Id == InPut. CusetomOrder_Id);
            if (cusetomOrder.State == "已分配") return new ApiResponse("工单已经分配", false, null);
            if (cusetomOrder == null) return new ApiResponse("未查询到工单", false, null);
            if(cusetomOrder.cusetomOrderLines.Count==0|| cusetomOrder.cusetomOrderLines==null) return new ApiResponse("工单内没有物料要出", false, null);
            cusetomOrder.cusetomOrderLines= cusetomOrder.cusetomOrderLines.OrderBy(x=> int.Parse(x.slotNum)).ToList();//2024-10-24新增
            //检查上一个工单是否完成了
            var neetOutMaterialChecks = await NeetOutMaterial_res.WithDetailsAsync();
            List<NeetOutMaterial> neetOutMaterialCheck = await neetOutMaterialChecks.Where(x => x.Material.BoxGrid == null).ToListAsync();
          
          
            //找出要出的料
            List<MaterialBase> materialBases = MaterialBase_res.WithDetails().ToList();   
            materialBases = materialBases.Where(x => cusetomOrder.cusetomOrderLines.Any(y => y.reelId == x.MaterialCode)&&x.BoxGrid!=null).ToList();
            if (materialBases.Count == 0) return new ApiResponse("工单中的物料有不在箱内,无法分配", false, null);
            List<TaskOrder> taskOrdercheck = await TaskOrder_res.GetListAsync(x=>x.OrderNo!=null);
            bool res=   taskOrdercheck.Any(x => materialBases.Any(y => y.BoxGrid.TheBox.Id_Box == x.Id_Box));
            if (res)
            {
                List<string> boxCodes = taskOrdercheck.Where(x => materialBases.Any(y => y.BoxGrid.TheBox.Id_Box == x.Id_Box)).Select(x => x.Box.BoxCode).ToList();
                string formattedBoxCodes = String.Join(", ", boxCodes);
                return new ApiResponse($"任务单中有料盒{formattedBoxCodes}被添加到任务,暂时不允许分配", false, null);
            }
               
            //creater neetOutMaterial
            List<NeetOutMaterial> neetOutMaterials = new List<NeetOutMaterial>();
            foreach (var outItem in cusetomOrder.cusetomOrderLines)
            {
                foreach (var materialBase in materialBases)
                {
                    if (materialBase.MaterialCode == outItem.reelId)
                    {

                        NeetOutMaterial neetOutMaterial = new NeetOutMaterial();
                        int count= materialBases.Where(x => x.MaterialName == materialBase.MaterialName).Count();
                        if (count >= 1)//同类型物料不止一个
                        {
                            List<NeetOutMaterial> neetOutMaterialsMode = neetOutMaterials.Where(x => x.Material.MaterialName == materialBase.MaterialName).ToList();
                            int neetquantity = int.Parse(outItem.quantity) - (int)neetOutMaterialsMode.Sum(x => x.NeetQuantity);
                            //if (neetquantity <= 0)
                            //{
                            //    continue;
                            //}//2024-10-24新增
                            //if (materialBase.Quantity > neetquantity)
                            //{
                            //    neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, cusetomOrder.hSerial, neetquantity, cusetomOrder.moCode, outItem.slotNum, null);
                            //}//2024-10-24新增

                            if (count-1 == neetOutMaterialsMode.Count)//最后一个
                            {
                        
                                neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, cusetomOrder.hSerial, neetquantity, cusetomOrder.moCode, outItem.slotNum,null);
                            }
                            else
                            {

                                neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, cusetomOrder.hSerial, materialBase.Quantity, cusetomOrder.moCode, outItem.slotNum,null);
                            }
                    

                        }
                        else//同类型物料有一个
                        {
                            neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, cusetomOrder.hSerial, int.Parse(outItem.quantity), cusetomOrder.moCode, outItem.slotNum, null);
                        }
        
                        neetOutMaterials.Add(neetOutMaterial);
                        materialBase.NeetOutMaterials.Add(neetOutMaterial);
                        if(outItem.reelId==materialBase.MaterialCode)
                        {
                            outItem.State = "已分配";
                        }
                    }
                }
            }
            await NeetOutMaterial_res.InsertManyAsync(neetOutMaterials);
            //creater taskorder
            materialBases = materialBases.DistinctBy(x => x.BoxGrid.TheBox.BoxCode).ToList();
            List<TaskOrder> taskOrders = await TaskOrder_res.GetListAsync();
            materialBases = materialBases.Where(x => !taskOrders.Any(y => y.Id_Box == x.BoxGrid.TheBox.Id_Box)).ToList();
            materialBases = materialBases.Where(x => x.BoxGrid.TheBox.WarehouseLine != null).ToList();

           
            foreach (var item in materialBases)
            {
                TaskOrder taskOrder = new TaskOrder();
                if (InPut.Machine == "2")
                {
                    taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, "LT_CONVEYOR_INPUT:POINT:26873:16077", cusetomOrder.hSerial);
                }
                else if (InPut.Machine == "3")
                {
                    SowingWallLine sowingWallLine= await sowingwallLine_res.FirstOrDefaultAsync(x => x.IsOccupy == false && string.IsNullOrEmpty(x.BoxCode));
                    if (sowingWallLine==null)
                    {
                        continue;
                    }      
                   taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, sowingWallLine.SowingWallLine_Name, "pda");
                   sowingWallLine.IsOccupy = true;
                   await sowingwallLine_res.UpdateAsync(sowingWallLine);
                }
                else
                {
                    taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, "LT_CONVEYOR_INPUT:POINT:26873:24239", cusetomOrder.hSerial);
                }
                await TaskOrder_res.InsertAsync(taskOrder);
            }
            //update cusetomOrder cusetomOrderline
            foreach (var item in cusetomOrder.cusetomOrderLines)
            {
                if (item.State == null)
                {
                    item.State = "缺料,不分配";
                }
            }
            cusetomOrder.State = "已分配";
            cusetomOrder.UpdateTime = DateTime.Now;
            await cusetom_order_res.UpdateAsync(cusetomOrder);
            return new ApiResponse("分配成功", true, null);
        }
        public async Task<ApiResponse> CreateTaskManyNeetOut(InPut_BaseService20 InPut)
        {
            var cusetomOrders = await cusetom_order_res.WithDetailsAsync();
            CusetomOrder cusetomOrder = await cusetomOrders.FirstOrDefaultAsync(x => x.CusetomOrder_Id == InPut.CusetomOrder_Id);
            if (cusetomOrder.State == "已分配") return new ApiResponse("工单已经分配", false, null);
            if (cusetomOrder == null) return new ApiResponse("未查询到工单", false, null);
            if (cusetomOrder.cusetomOrderLines.Count == 0 || cusetomOrder.cusetomOrderLines == null) return new ApiResponse("工单内没有物料要出", false, null);
            //检查上一个工单是否完成了
            //List<NeetOutMaterial> neetOutMaterialCheck = await NeetOutMaterial_res.GetListAsync();
            //List<TaskOrder> taskOrdercheck = await TaskOrder_res.GetListAsync(x => x.OrderNo != null);
            //if (neetOutMaterialCheck.Count > 0 || taskOrdercheck.Count > 0) return new ApiResponse("有工单任务/工单需求未完成", false, null);
            //找出要出的料
            List<MaterialBase> materialBases = MaterialBase_res.WithDetails().ToList();
            materialBases = materialBases.Where(x => cusetomOrder.cusetomOrderLines.Any(y => y.reelId == x.MaterialCode) && x.BoxGrid != null).ToList();
            if (materialBases.Count == 0) return new ApiResponse("工单中的物料不在箱内,无法分配", false, null);
            //creater neetOutMaterial
            List<NeetOutMaterial> neetOutMaterials = new List<NeetOutMaterial>();
            foreach (var outItem in cusetomOrder.cusetomOrderLines)
            {
                foreach (var materialBase in materialBases)
                {
                    if (materialBase.MaterialCode == outItem.reelId)
                    {

                        NeetOutMaterial neetOutMaterial = new NeetOutMaterial();
                        int count = materialBases.Where(x => x.MaterialName == materialBase.MaterialName).Count();
                        if (count >= 1)
                        {
                            List<NeetOutMaterial> neetOutMaterialsMode = neetOutMaterials.Where(x => x.Material.MaterialName == materialBase.MaterialName).ToList();
                            if (count - 1 == neetOutMaterialsMode.Count)
                            {
                                int neetquantity = int.Parse(outItem.quantity) - (int)neetOutMaterialsMode.Sum(x => x.NeetQuantity);
                                neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, cusetomOrder.hSerial, neetquantity, cusetomOrder.moCode, outItem.slotNum,null);
                            }
                            else
                            {
                                neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, cusetomOrder.hSerial, materialBase.Quantity, cusetomOrder.moCode, outItem.slotNum,null);
                            }


                        }
                        else
                        {
                            neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, cusetomOrder.hSerial, int.Parse(outItem.quantity), cusetomOrder.moCode, outItem.slotNum,null);
                        }

                        neetOutMaterials.Add(neetOutMaterial);
                        materialBase.NeetOutMaterials.Add(neetOutMaterial);
                        if (outItem.reelId == materialBase.MaterialCode)
                        {
                            outItem.State = "已分配";
                        }
                    }
                }
            }
            await NeetOutMaterial_res.InsertManyAsync(neetOutMaterials);
            //creater taskorder
            materialBases = materialBases.DistinctBy(x => x.BoxGrid.TheBox.BoxCode).ToList();
            List<TaskOrder> taskOrders = await TaskOrder_res.GetListAsync();
            materialBases = materialBases.Where(x => !taskOrders.Any(y => y.Id_Box == x.BoxGrid.TheBox.Id_Box)).ToList();
            materialBases = materialBases.Where(x => x.BoxGrid.TheBox.WarehouseLine != null).ToList();
            foreach (var item in materialBases)
            {
                TaskOrder taskOrder = new TaskOrder();
                if (InPut.Machine == "2")
                {
                    taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, "LT_CONVEYOR_INPUT:POINT:26873:16077", cusetomOrder.hSerial);
                }
                else
                {
                    taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, "LT_CONVEYOR_INPUT:POINT:26873:24239", cusetomOrder.hSerial);
                }
                await TaskOrder_res.InsertAsync(taskOrder);
            }
            //update cusetomOrder cusetomOrderline
            foreach (var item in cusetomOrder.cusetomOrderLines)
            {
                if (item.State == null)
                {
                    item.State = "缺料,不分配";
                }
            }
            cusetomOrder.State = "已分配";
            cusetomOrder.UpdateTime = DateTime.Now;
            await cusetom_order_res.UpdateAsync(cusetomOrder);
            return new ApiResponse("分配成功", true, null);
        }//合并分配
        public async Task<ApiResponse> CreateTaskManyNeetOutNew(InPut_BaseService21 InPut)
        {
            var neetOutMaterialsQuery = await NeetOutMaterial_res.WithDetailsAsync();
            var neetOutMateriailsError = neetOutMaterialsQuery.Where(x => x.remark.Contains("缺料22")).
                                   Select(x => new {
                                       MaterialName = x.Material.MaterialName,
                                       MaterialCode = x.Material.MaterialCode,
                                       NeetQuantity = x.NeetQuantity,
                                       OrderNo = x.OrderNo,
                                       moCode = x.moCode,
                                       remark = x.remark

                                   }).ToList();
            var cusetoms=   await cusetom_order_res.WithDetailsAsync();
            List<CusetomOrder> cusetomOrders = new List<CusetomOrder>();
            foreach (var item in InPut.hSerials)
            {
                cusetomOrders.Add(await cusetoms.FirstOrDefaultAsync(x =>x.hSerial==item));
            }
            
            if (cusetomOrders.Any(x => x.State == "已分配")) return new ApiResponse("有工单已经分配", true, neetOutMateriailsError);
            if (cusetomOrders.Count() == 0) return new ApiResponse("未查询到任何一个工单", true, neetOutMateriailsError);
            List<CusetomOrderLine> cusetomOrderLines= cusetomOrders.SelectMany(x=>x.cusetomOrderLines).ToList();//拿到所有工单明细
            var materialBasesTracking =  MaterialBase_res.WithDetails().AsNoTracking();
            List<MaterialBase> materialBases= materialBasesTracking.ToList();
            materialBases = materialBases.Where(x => cusetomOrderLines.Any(y => y.reelId == x.MaterialCode) && x.BoxGrid != null).ToList();//拿到所有物料

            List<MaterialBase> materialBasesTaskOrder = MaterialBase_res.WithDetails().ToList();
            materialBasesTaskOrder = materialBasesTaskOrder.Where(x => cusetomOrderLines.Any(y => y.reelId == x.MaterialCode) && x.BoxGrid != null).ToList();//AGV任务用
            List<TaskOrder> taskOrdercheck = await TaskOrder_res.GetListAsync(x=>x.OrderNo!=null);
            bool res = taskOrdercheck.Any(x => materialBasesTaskOrder.Any(y => y.BoxGrid.TheBox.Id_Box == x.Id_Box));
            if (res) return new ApiResponse("任务单中有料盒已被添加到任务,暂时不允许分配", true, neetOutMateriailsError);
            //creater neetOutMaterial
            List<NeetOutMaterial> neetOutMaterials = new List<NeetOutMaterial>();
            foreach (var cusetomOrder in cusetomOrders)
            {
                foreach (var cusetomOrderLine in cusetomOrder.cusetomOrderLines)
                {
                    MaterialBase materialBase =   materialBases. FirstOrDefault(x => x.MaterialCode == cusetomOrderLine.reelId);
                 
                    if (materialBase == null)
                    {
                        if (InPut.IsEnable)
                        {
                            cusetomOrderLine.State = "缺料不分配";
                        }
                        continue;
                    }
                        
                    NeetOutMaterial neetOutMaterial= new NeetOutMaterial();
                    //测算需求数量
                    int neetquantity;
                    string remark;
                    if(cusetomOrder.cusetomOrderLines.Count(x => x.mtrlCode == cusetomOrderLine.mtrlCode) > 1)
                    {//多个LPN                       
                       
                        if(!neetOutMaterials.Any(x => x.Material.MaterialName == materialBase.MaterialName && x.OrderNo == cusetomOrder.hSerial))
                        {//是第一个
                         //需求数量<=库存
                            if (int.Parse(cusetomOrderLine.quantity) <= materialBase.Quantity)
                            {
                                neetquantity = int.Parse(cusetomOrderLine.quantity);
                                remark = cusetomOrderLine.quantity;
                            }
                            else
                            {//需求数量>库存  缺料
                                //如果库存为0了
                                if ((int)materialBase.Quantity <= 0)
                                {
                                    if (InPut.IsEnable)
                                    {
                                        cusetomOrderLine.State = "缺料不分配";
                                    }
                             
                                    continue;
                                }
                                neetquantity = (int)materialBase.Quantity;
                                remark = cusetomOrderLine.quantity + "-缺料";
                            }
                        }
                        else
                        {//不是第一个
                             int quantitySum=(int)neetOutMaterials.Where(x => x.Material.MaterialName == materialBase.MaterialName && x.OrderNo == cusetomOrder.hSerial).Select(x=>x.NeetQuantity).Sum();
                            if (int.Parse( cusetomOrderLine.quantity) <= quantitySum)
                            {
                                //第一个LPN已经满足需求
                                if (InPut.IsEnable)
                                {
                                    cusetomOrderLine.State = "缺料不分配";
                                }
                                continue;
                            }
                            if(materialBase.Quantity>= int.Parse(cusetomOrderLine.quantity) -  quantitySum)
                            {//库存数量>=需求数量
                                neetquantity = int.Parse(cusetomOrderLine.quantity) - quantitySum;
                                remark = cusetomOrderLine.quantity;
                            }
                            else
                            {//缺料
                                     //如果库存为0了
                                if ((int)materialBase.Quantity <= 0)
                                {
                                    if (InPut.IsEnable)
                                    {
                                        cusetomOrderLine.State = "缺料不分配";
                                    }
                                    continue;
                                }
                                neetquantity = (int)materialBase.Quantity;
                                remark =  cusetomOrderLine.quantity + "-缺料";
                            }
                        }


                    }
                    else
                    { //一个LPN
                        //需求数量<=库存
                        if (int.Parse( cusetomOrderLine.quantity) <= materialBase.Quantity)
                        {
                            neetquantity = int.Parse( cusetomOrderLine.quantity);
                            remark = cusetomOrderLine.quantity;
                     
                        }
                        else
                        {//需求数量>库存  缺料
                         //如果库存为0了
                            if ((int)materialBase.Quantity <= 0)
                            {
                                if (InPut.IsEnable)
                                {
                                    cusetomOrderLine.State = "缺料不分配";
                                }
                                continue;
                            }
                            neetquantity = (int)materialBase.Quantity;
                            remark = cusetomOrderLine.quantity + "-缺料";
                        }                      
                    }




                    MaterialBase materialBaseSaveChange=    await MaterialBase_res.FirstOrDefaultAsync(x => x.Id_Materialbase == materialBase.Id_Materialbase);
                    neetOutMaterial=   neetOutMaterial.AddNeetOutMaterial(materialBaseSaveChange, cusetomOrder.hSerial, neetquantity, cusetomOrder.moCode, cusetomOrderLine.slotNum,remark);
                    neetOutMaterials.Add(neetOutMaterial);
                    materialBase.Quantity=materialBase.Quantity- neetquantity;    
                    if(string.IsNullOrEmpty(cusetomOrderLine.State))
                    {
                        if (InPut.IsEnable)
                        {
                            cusetomOrderLine.State = "已分配";
                        }
                 
                    }     
                    
                }
                if (InPut.IsEnable)
                {
                    cusetomOrder.State = "已分配";
                    cusetomOrder.UpdateTime = DateTime.Now;
                }
            
             
            }
            //creater TaskOrder
            materialBasesTaskOrder = materialBasesTaskOrder.DistinctBy(x => x.BoxGrid.TheBox.BoxCode).ToList();
            List<TaskOrder> taskOrders = await TaskOrder_res.GetListAsync();
            materialBasesTaskOrder = materialBasesTaskOrder.Where(x => !taskOrders.Any(y => y.Id_Box == x.BoxGrid.TheBox.Id_Box)).ToList();
            materialBasesTaskOrder = materialBasesTaskOrder.Where(x => x.BoxGrid.TheBox.WarehouseLine != null).ToList();
            List<SowingWallLine> sowingWallLines = await sowingwallLine_res.GetListAsync(x => x.IsOccupy == false && string.IsNullOrEmpty(x.BoxCode));
            foreach (var item in materialBasesTaskOrder)
            {
                TaskOrder taskOrder = new TaskOrder();
                if (InPut.Machine == "2")
                {
                    taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, "LT_CONVEYOR_INPUT:POINT:26873:16077", "合并工单");
                }
                else if (InPut.Machine == "3")
                {
                 
             
                    SowingWallLine sowingWallLine = sowingWallLines.FirstOrDefault(x=>x.IsOccupy==false);
                    if(sowingWallLine==null)
                    {
                        return new ApiResponse("缓存位不足", false, null);
                    }
                    taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, sowingWallLine.SowingWallLine_Name, "pda");
                    sowingWallLine.IsOccupy = true;
                   

                 
                }
                else
                {
                    taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, "LT_CONVEYOR_INPUT:POINT:26873:24239", "合并工单");
                }
                if (InPut.IsEnable)
                {
                    await TaskOrder_res.InsertAsync(taskOrder);
                }
            }
            if (InPut.IsEnable)
            {
                //await cusetom_order_res.UpdateManyAsync(cusetomOrders);
                await NeetOutMaterial_res.InsertManyAsync(neetOutMaterials);
         
            }
            await sowingwallLine_res.UpdateManyAsync(sowingWallLines);
            var neetOutMateriailsInfo= neetOutMaterials.Where(x=>x.remark.Contains("缺料")).
                                       Select(x => new { MaterialName =x.Material.MaterialName, 
                                                         MaterialCode =x.Material.MaterialCode,
                                                         NeetQuantity = x.NeetQuantity,
                                                         OrderNo=x.OrderNo,
                                                         moCode=x.moCode,
                                                         remark = x.remark

                                       }). ToList();
            return new ApiResponse("分配成功", true, neetOutMateriailsInfo);

        }//合并工单新
        public async Task<ApiResponse> GetListCusetomLine(Guid CusetomOrder_Id)//获取mes出库工单详情
        {
            try
            {
                List<CusetomOrderLine> cusetomOrderLines= await cusetom_order_line_res.GetListAsync(x=>x.CusetomOrder.CusetomOrder_Id==CusetomOrder_Id);
                return new ApiResponse("获取成功", true, cusetomOrderLines);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync("CusetomOrder_Id", "GetListCusetomLine");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> DeleteNeetMaterial(string MaterialCode)//删除需出料
        {
          NeetOutMaterial neetOutMaterial= await NeetOutMaterial_res.FirstOrDefaultAsync(x=>x.Material.MaterialCode==MaterialCode);
            if (neetOutMaterial != null)
            {
                await NeetOutMaterial_res.DeleteAsync(neetOutMaterial);
            }
            return new ApiResponse("删除成功",true,null);
        }
        public async Task<ApiResponse> CheckNeetTask()//验证是否还有未出料
        {

                 var neetOutMaterialChecks = await NeetOutMaterial_res.WithDetailsAsync();          
                List<NeetOutMaterial> neetOutMaterialCheck = await   neetOutMaterialChecks.Where(x => x.Material.BoxGrid == null).ToListAsync();
                List<TaskOrder> taskOrdercheck = await TaskOrder_res.GetListAsync(x => x.OrderNo != null);
                if (neetOutMaterialCheck.Count > 0 || taskOrdercheck.Count > 0) return new ApiResponse("有工单任务/工单需求未完成", false, null);
                return new ApiResponse("工单都完成了", true, null);
        }
        public async Task<ApiResponse> DeleteWaste()//删出废料
        {
            try
            {
                var NeetOutMaterials = await NeetOutMaterial_res.WithDetailsAsync();
                List<NeetOutMaterial> neetOutMaterials = await NeetOutMaterials.Where(x => x.Material.BoxGrid == null).ToListAsync();
                await NeetOutMaterial_res.DeleteManyAsync(neetOutMaterials);
                return new ApiResponse("清除成功", true, null);
            }catch(Exception ex)
            {
                loginHelper.LoginAsync("CusetomOrder_Id", "DeleteWaste");
                return new ApiResponse("内部错误服务器", false, null);
            }


        }
        public async Task<ApiResponse> ReMoveTaskNeetOut(Guid CusetomOrder_Id)//取消分配
        {
            try
            {
                var cusetomorders = await cusetom_order_res.WithDetailsAsync();
                CusetomOrder cusetomOrder = await cusetomorders.FirstOrDefaultAsync(x => x.CusetomOrder_Id == CusetomOrder_Id);
                if (cusetomOrder == null)
                {
                    return new ApiResponse("未查询到工单", true, null);
                }
                bool res = await TaskOrder_res.AnyAsync(x => x.OrderNo == cusetomOrder.hSerial && x.State == "已下发");
                if (res) return new ApiResponse("已经有下发的任务了,无法取消分配了", true, null);
                //update cusetomorder cusetmorderline
                cusetomOrder.State = "未分配";
                cusetomOrder.cusetomOrderLines.ForEach(x => x.State = "未分配");
                await cusetom_order_res.UpdateAsync(cusetomOrder);
                //delete neetoutmaterial
                List<NeetOutMaterial> neetOutMaterials = await NeetOutMaterial_res.GetListAsync(x => x.OrderNo == cusetomOrder.hSerial);
                await NeetOutMaterial_res.DeleteManyAsync(neetOutMaterials);
                //delete taskorder
                List<TaskOrder> taskOrders = await TaskOrder_res.GetListAsync(x => x.OrderNo == cusetomOrder.hSerial);
                await TaskOrder_res.DeleteManyAsync(taskOrders);
                return new ApiResponse("解除分配成功", true, null);
            }catch(Exception ex)
            {
                loginHelper.LoginAsync("CusetomOrder_Id:"+ CusetomOrder_Id, "ReMoveTaskNeetOut");
                return new ApiResponse("内部错误服务器", false, null);
            }
        


        }
        public async Task<ApiResponse> UpdateMaterialQuantity(InPut_BaseService19 InPut)//修改库存数量
        {
            try
            {
                MaterialBase materialBase = await MaterialBase_res.FirstOrDefaultAsync(x => x.MaterialCode == InPut.MaterialCode);
                if (materialBase == null) return new ApiResponse("未找到物料", false, null);
                materialBase.Quantity = int.Parse(InPut.Quantity);
                await MaterialBase_res.UpdateAsync(materialBase);
                return new ApiResponse("修改成功", true, null);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(InPut, "UpdateMaterialQuantity");
                return new ApiResponse("内部服务器错误", false, null);
            }
        }
        public async Task<ApiResponse> DeleteOrder(List<Guid> CusetomOrder_IdS)
        {
            try
            {
                List<CusetomOrder> cusetomOrders = await cusetom_order_res.GetListAsync(x => CusetomOrder_IdS.Any(y => y == x.CusetomOrder_Id));
                if (cusetomOrders.Any(x => x.State == "已分配"))
                {
                    return new ApiResponse("无法删除,包含已分配得工单", false, null);
                }
                await cusetom_order_res.DeleteManyAsync(cusetomOrders);
                return new ApiResponse("删除成功", true, null);
            }
            catch (Exception ex) 
            {


                loginHelper.LoginAsync(CusetomOrder_IdS, "DeleteOrder");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> Create_SowingWall(InPut_BaseService22 InPut)
        {
            try
            {
                SowingWall sowingWall = new SowingWall();
                sowingWall = sowingWall.AddSowingWall(InPut.SowingWall_Name, InPut.SowingWall_Code, InPut.Xaxis, InPut.Yaxis, InPut.Machine);
                if (sowingWall == null)
                {
                    return new ApiResponse("添加失败", false, null);
                }
                await sowingwall_res.InsertAsync(sowingWall);
                return new ApiResponse("添加成功", false, null);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(InPut, "Create_SowingWall");
                return new ApiResponse("ERROR-Create_SowingWall", false, ex);
            }
        }
        public async Task<ApiResponse> Create_TaskOrder_Pda(InPut_BaseService23 InPut)//pda创建任务
        {
             Box box=   await Box_res.FirstOrDefaultAsync(x => x.BoxCode == InPut.BoxCode);
            if (box == null) return new ApiResponse("料箱不存在", false, null);
            if (box.Id_WarehouseLine != null) return new ApiResponse("料箱在库内,无法创建任务", false, null);
            SowingWallLine sowingWallLine=  await sowingwallLine_res.FirstOrDefaultAsync(x=>x.SowingWallLine_Name==InPut.SowingWallLine_Name&&x.IsOccupy==true&&x.BoxCode==InPut.BoxCode);
            if (sowingWallLine == null) {

             sowingWallLine=   await sowingwallLine_res.FirstOrDefaultAsync(x => x.SowingWallLine_Name == InPut.SowingWallLine_Name && x.IsOccupy == false);
                if(sowingWallLine== null) return new ApiResponse("该播种墙没有空位", false, null);

            } 
            WarehouseLine warehouseLine = await WarehouseLine_res.FirstOrDefaultAsync(x => x.Box == null && x.IsEnable == true && x.IsOccupy == false);
            //create taskorder
            TaskOrder taskOrder = new TaskOrder();
            taskOrder.OrderNo = "pda";
            taskOrder.Box = box;
            taskOrder.Type = "入库";
            taskOrder.WarehouseCode = warehouseLine.WarehouseLineCode;
            taskOrder.InlethouseCode = sowingWallLine.SowingWallLine_Name;
            taskOrder.CreatTime = DateTime.Now;
            taskOrder.State = "未下发";
            taskOrder.TaskOrderCode = ExtendRandom.CreateRandom();
            //update box warehouseLine  
            box.TaskOrder = taskOrder;
            warehouseLine.IsOccupy = true;
            // update sowingwallline
            sowingWallLine.IsOccupy = true;
            sowingWallLine.BoxCode = box.BoxCode;

            await WarehouseLine_res.UpdateAsync(warehouseLine);
            await sowingwallLine_res.UpdateAsync(sowingWallLine);
            await Box_res.UpdateAsync(box);
            await TaskOrder_res.InsertAsync(taskOrder);
            return new ApiResponse("创建成功", true, null);
        }
        public async Task<ApiResponse> Send_TaskOrder_Pda()
        {
            List<TaskOrder> taskOrders = await context.taskOrders.Include(x=>x.Box).Where (x=>x.OrderNo == "pda" && x.State == "未下发"&&x.Type=="入库").ToListAsync();
            foreach (var taskorder in taskOrders)
            {
                Ess_Input ess_Input = new Ess_Input();
                ess_Input.taskType = "putaway";
                ess_Input.taskGroupCode = "taskGroupCode-001";
                ess_Input.groupPriority = 0;
                List<Tasks> data = new List<Tasks>();
                Tasks ta = new Tasks();
                ta.taskCode = taskorder.TaskOrderCode;
                ta.taskPriority = 0;
                data.Add(ta);
                ess_Input.tasks = data;
                TaskDescribe td = new TaskDescribe();
                td.containerCode = taskorder.Box.BoxCode;
                td.containerType = "CT_KUBOT_STANDARD";
                td.storageTag = "";
                td.fromLocationCode = taskorder.InlethouseCode;
                td.toLocationCode = taskorder.WarehouseCode;
                td.toStationCode = "haiport_station_1";
                td.isPutaway = false;
                ta.taskDescribe = td;
                //send
                try
                {
                    var url = $"http://172.23.1.15:9046/task/create";
                    string result = await url.PostJsonAsync(ess_Input).ReceiveString();
                    ApiResponseEss Response = JsonConvert.DeserializeObject<ApiResponseEss>(result);
                    string res = Response.data.ToString();
                    if (Response.msg == "success")
                    {
                        taskorder.State= "已下发";
                    }
                }catch(Exception ex)
                {
                    loginHelper.LoginAsync(taskorder.TaskOrderCode, "Send_TaskOrder_Pda");
                  
                }
           
            }
            await TaskOrder_res.UpdateManyAsync(taskOrders);
            return new ApiResponse("下发成功", true, null);
        }
        public async Task<ApiResponse> Update_SowingWallLine_Pda(string BoxCode)
        {
           SowingWallLine sowingWallLine=  await sowingwallLine_res.FirstOrDefaultAsync(x=>x.BoxCode == BoxCode);
           if (sowingWallLine == null) return new ApiResponse("该料箱没有绑定播种墙", false, null);
            TaskOrder taskOrder=   await TaskOrder_res.FirstOrDefaultAsync(x => x.Box.BoxCode == BoxCode);
            if(taskOrder != null) return new ApiResponse("该料箱还存在任务,无发解除", false, null);

            sowingWallLine.IsOccupy = false;
           sowingWallLine.BoxCode = null;
           await sowingwallLine_res.UpdateAsync(sowingWallLine);

            Logger.LogWarning("释放库位", $"{sowingWallLine.SowingWallLine_Name}_{sowingWallLine.BoxCode}");
            return new ApiResponse("更新成功", true, null);
        }
    }
}
